/* 上传图片组件，用浓郁图片的上传 */
<template>
  <div>
    <!-- 
      list-type 文件列表的类型
      limit 最大允许上传个数
      on-preview 点击文件列表中已上传的文件时的钩子
      on-remove 文件列表移除文件时的钩子
      action 上传的地址
      auto-upload 是否在选取文件后立即进行上传
      accept 接受上传的文件类型
      before-upload 上传文件之前的钩子，参数为上传的文件
      on-success 文件上传成功
     -->

     <!-- <el-upload
        :action="uploadImgUrl"
        accept=".png, .jpg"
        :limit="5"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-success="handleAvatarSuccess"
        :file-list="imageList"
        :headers="headers"
        :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过2M</div>
    </el-upload> -->

    <!-- <el-upload
      :action="uploadImgUrl"
      accept=".png, .jpg"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-success="handleAvatarSuccess"
      :file-list="imageList"
      :headers="headers"
      :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
  </el-upload> -->

  
     
    <el-upload
      ref="uploadImg"
      :action="url"
      :limit="fileLimit"
      list-type="picture-card"
      :class="{ 'choose-img-none': fileList.length > fileLimit - 1 }"
      :on-preview="handleUploadPreview"
      :on-remove="handleUploadRemove"
      :disabled="isDisabled"
      :headers="headers"
      :auto-upload="true"
      :accept="uploadImageAccept"
      :before-upload="handleBeforeUpload"
      :on-success="handleOnSuccess"
      :file-list="fileList"
    >
      <i class="el-icon-plus" />
      <!-- <i class="el-icon-upload"></i> -->
      <!-- <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
      <div class="el-upload__tip" style="margin-top: 0px;" slot="tip">
        <span style="color: #BFBFBF">支持JPG、JPEG、PNG格式，10M以内</span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisibleImg" :modal="true" :modal-append-to-body="false" append-to-body>
      <img width="100%" :src="previewImgUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
// import store from "@/store";
// import router, { resetRouter } from "@/router";
// import { webApi } from "@/api/commonApi";
// import { getToken } from "@/utils/auth";
import { getToken } from "@/utils/auth";
import openWindow from "@/utils/open-window"
export default {
  props: {
    tagData: {
      type: Object
    },
    lastUrl: {
      type: String,
      default: ''
    },
    fileLimit: {        // 最大允许上传图片个数
      type: Number,
      default: 1,
    },
    imageData: {        // 图片数据
      type: Array,
      default: [],
    },
    isDisabled: {
      type: Boolean,
      default: false,
    },
    indexDefault:{
      type:Number,
      default:-1
    },
    uploadImageAccept:{
       type:String,
      default: 'image/jpg,image/jpeg,image/png'
    },
    isOCR: {
      type: Boolean,
      default: false
    },
    OCRType: {
      type: String,
      default: '-1'
    },
    isEctype: { //是否是正本(是 1 否 2)
      type: String,
      default: ""
    }
  },
  data() {
    return {
      // item: undefined,
      // url: process.env.VUE_APP_BASE_API + "/obs/upload"
      url: process.env.VUE_APP_BASE_API + "/obs/upload" + this.lastUrl,
      headers: {Authorization: "Bearer " + getToken(),},
      dialogVisibleImg: false, // 是否显示弹窗
      previewImgUrl: "",        // 图片url
      fileList: [],
      imageList: [],
      imgPath: process.env.VUE_APP_DOWNLOAD_API // 图片下载地址前置
    };
  },
  mounted() {
    // console.log('url=', this.url);
    // console.log('headers=', this.headers);
    // console.log('tagData=', this.tagData);
    // this.item = this.tagData;
  },
  watch: {
    imageData: {
      handler(newVal) {
        // 通过深度拷贝对象解除互相绑定关系,直接赋值会引起重复的数据更新
        if(newVal.length !== this.fileList.length){
          this.fileList = JSON.parse(JSON.stringify(newVal));
          this.imageList = JSON.parse(JSON.stringify(newVal));
        }else{
          let bret = false;
          newVal.some(item=>{
            bret = false;
            this.imageList.some(val=>{
              if(item.id == val.id){
                bret = true;
                return bret;
              }
            })
          })
          if (bret == false) {
            this.fileList = JSON.parse(JSON.stringify(newVal));
            this.imageList = JSON.parse(JSON.stringify(newVal));
          }
        }
      },
      deep: true,
      immediate: true,
    },
    isDisabled:{
      handler(newVal){
        this.isDisabled = newVal
        // console.log(newVal)
      },
      deep: true,
      immediate: true,
    }
  },
  methods: {
    
    /**
     * 预览图片 -- 点击文件列表中已上传的文件时的钩子
     */
    async handleUploadPreview(file) {
      console.log(file)
      if(file.response){
          this.previewImgUrl = process.env.VUE_APP_BASE_API + '/obs/download?id=' + file.response.data.id;
        }else{
          this.previewImgUrl = process.env.VUE_APP_BASE_API + '/obs/download?id=' + file.id;
        }
      // if(file.name.indexOf('.pdf')>-1){
      //   let flowId=file.response?file.response.data:file.flowId
      // //  const res = await webApi.getUploadImgInfoById({ flowIds: flowId });
      //   openWindow(this.imgPath + res.data[0].storePath,'')
      // }else{
      //   this.previewImgUrl = file.url;
        this.dialogVisibleImg = true;
      // }  
    },
    
    /**
     * 上传图片之前判断
     */
    handleBeforeUpload(file) {
      let type = file.type;
      // console.log('url=', this.url);
      // console.log('headers=', this.headers);
      // console.log('file=', file.type);
      // type = type.indexOf('pdf') > -1 ?'.pdf' : type;
      // console.log('type=', type);
      // console.log('uploadImageAccept=', this.uploadImageAccept);
      const size = file.size / 1024 / 1024;
      // const size = file.size / 1024 / 1024 < 10;
      // if(this.uploadImageAccept.indexOf(type) < 0){
      //    this.$message({
      //     type: "error",
      //     message: "上传文件格式不正确,请重新上传!",
      //     duration: 1000,
      //   });
      //   return false;
      // }
      if (size > 10) {
        this.$message({
          type: "error",
          message: "上传文件不能超过10M!",
          duration: 1000,
        });
        return false;
      }
    },
    
    /**
     * 删除图片
     */
    handleUploadRemove(file, fileList) {
      this.fileList.forEach((item, index ) => {
        if (file.response && item.response) {
          if (item.response.data == file.response.data) {
            this.imageList.splice(index, 1);
            this.fileList.splice(index, 1);
          }
        } else {
          if (item.url == file.url) {
            this.imageList.splice(index, 1);
            this.fileList.splice(index, 1);
          }
        }
      });
      this.$emit("uploadRemove", this.indexDefault);
      this.$emit("imageInfo", this.imageList, this.tagData, this.indexDefault); 
    },
    
    /**
     * 上传成功时
     */
    handleOnSuccess(response, file, fileList) {
      // console.log('上传文件response=', response);
      // console.log('fileList=', fileList);
      // console.log('file=', file);
      if (response.code == 200) {
        this.fileList.push(file);
        this.getImageInfo(response.data, file);
      }
      /*
      if (response.code === 20000) {
        this.fileList.push(file);
        this.getImageInfo(response.data);
      } else if (response.code === 20003 || response.code === 40003) {
        // token失效，清除登陆数据并跳到登陆页面
        this.$alert("您的登录信息已失效,请重新登录!", "提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
          showClose: false,
          closeOnClickModal: false,
        }).then(() => {
          // 清除所有访问的标签页
          store.dispatch("tagsView/delAllVisitedViews", {}, { root: true });
          // 清除所有访问的缓存标签页
          store.dispatch("tagsView/delAllCachedViews", {}, { root: true });
          // 重置数据
          store.dispatch("user/resetData", {}).then(() => {
            resetRouter();
            location.reload();
          });
        });
      } else {
        this.fileList = [];
      }
      */
    },
    
    /**
     * 根据id获取当前图片信息
     */
    async getImageInfo(rsp, file) {
      /*
      const res = await webApi.getUploadImgInfoById({ flowIds: flowId });
      if (res.code === 20000) {
        let ocrInfo = null;
        if(this.isOCR){
          console.log('准备OCR');
          const query = {
            urlImage: this.imgPath + res.data[0].storePath,
            flag: this.OCRType, 
            isEctype: this.isEctype
          };
          console.log('query=', query);
          const { data } = await webApi.getOCRInfo(query);
          ocrInfo = data;
        } */
        this.imageList.push({
            id: rsp.id,
            name: rsp.objectOriginalName,
            // storePath:res.data[0].storePath,
            url: rsp.objectUrl,
            size: file.size,
            // ocrInfo
         })
        this.$emit("imageInfo", this.imageList, this.tagData, this.indexDefault);
      // }
      
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .choose-img-none .el-upload--picture-card {
  display: none;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  margin: 0px 8px 0px 0px;
}

::v-deep .el-upload-list--picture-card {
  // display: inline-block;
  height: 156px;
}

// ::v-deep .el-upload-list--picture-card .el-upload-list__item {
//   width: 110px;
//   height: 110px;
// }
</style>